package org.mobilertrain.qsbk;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import org.mobilertrain.qsbk.entity.Entity;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * A simple {@link Fragment} subclass.
 */
public class RecyclerFragment extends Fragment implements Callback<Entity> {


    private ItemAdapter adapter;

    public RecyclerFragment() {
        // Required empty public constructor
    }

    public static RecyclerFragment getInstance(String type) {
        RecyclerFragment fragment = new RecyclerFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type",type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_recycler, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        TextView textView = (TextView) view.findViewById(R.id.fragment_tv);
        String type = getArguments().getString("type");
//        textView.setText(type);
        BaseApplication application = (BaseApplication) getActivity().getApplication();
        application.getService().getList(type,1).enqueue(this);
        adapter = new ItemAdapter(getContext());
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onResponse(Call<Entity> call, Response<Entity> response) {
        Entity body = response.body();
        adapter.addALL(body.getItems());

    }

    @Override
    public void onFailure(Call<Entity> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(getContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
    }
}
